﻿using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;

namespace VivendoByte.UploaderWSS
{
    public partial class SharepointUrlControl : UserControl
    {
        #region Const
        const char SEPARATOR = '/';
        const string PROTOCOL_SEPARATOR = "//";
        const string FOLDER = "&Folder";
        const string WEBSITE = "&Website";
        const string DOCUMENT_LIBRARY = "&Document Library";
        #endregion

        #region Private fields (cache)
        Size buttonSize = new Size(10, 10);
        Point initial;
        Point final;
        Pen clearPen;
        Pen[] pens = new Pen[10]
        {
            Pens.Red,
            Pens.Green,
            Pens.SaddleBrown,
            Pens.Orange,
            Pens.LightBlue,
            Pens.Moccasin,
            Pens.DarkOliveGreen,
            Pens.PaleGreen,
            Pens.Cornsilk,
            Pens.Thistle
        };

        int numberOfParts = 0;
        string[] parts;
        Control selected;
        Dictionary<string, Control> controls = new Dictionary<string, Control>();
        #endregion

        #region ctor
        public SharepointUrlControl()
        {
            InitializeComponent();
            clearPen = new Pen(this.BackColor);
        }
        #endregion

        #region Public Property
        public string Url
        {
            get { return this.UrlTextBox.Text; }
            set { this.UrlTextBox.Text = value; }
        }
        #endregion

        #region OnPaint
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            int colorIndex = 0;
            float oldWidth = 0.0F;
            float totalWidth = 0.0F;
            Rectangle boundaries = this.UrlTextBox.Bounds;
            int yCoor = boundaries.Bottom + 2;
            string key;
            Button btn;

            // Remove the old lines
            e.Graphics.DrawLine(clearPen, new Point(0, yCoor), new Point(2000, yCoor));

            List<int> indexes = new List<int>();

            if (parts != null)
            {
                foreach (string s in parts)
                {
                    if (string.IsNullOrEmpty(s)) continue;

                    SizeF dim = e.Graphics.MeasureString(s, this.Font);

                    totalWidth = (totalWidth + dim.Width);

                    // Calculate the position of the line
                    initial = new Point((int)oldWidth, yCoor);
                    final = new Point((int)totalWidth, yCoor);
                    e.Graphics.DrawLine(pens[colorIndex++], initial, final);
                    key = "_" + colorIndex.ToString();
                    float pos = (oldWidth + (totalWidth - oldWidth) / 2) - 5;

                    if (!controls.ContainsKey(key))
                    {
                        btn = new Button();
                        btn.Location = new Point((int)pos, yCoor - 2);
                        btn.Size = buttonSize;
                        btn.ContextMenuStrip = this.ContextMenu;
                        btn.Tag = key;
                        btn.Click += new EventHandler(btn_Click);

                        controls.Add(key, btn);
                        this.Controls.Add(btn);
                    }
                    else
                    {
                        btn = (Button)controls[key];
                        btn.Location = new Point((int)pos, yCoor - 2);
                    }

                    oldWidth = totalWidth;
                }
            }
        }
        #endregion

        #region TextChanged
        private void UrlTextBox_TextChanged(object sender, EventArgs e)
        {
            int n = this.UrlTextBox.Text.Split(SEPARATOR).Length;
            parts = this.UrlTextBox.Text.Split(SEPARATOR);

            if (n != numberOfParts)
            {
                if (n < numberOfParts)
                {
                    for (int i = n; i <= numberOfParts; i++)
                    {
                        string key = "_" + i.ToString();
                        controls.Remove(key);
                        removeButtonWithTag(key);
                    }
                }

                numberOfParts = n;
            }

            this.Invalidate();
        }
        #endregion

        #region Get Partial Url
        public string GetPartialUrl(UrlPartEnum part)
        {
            StringBuilder bld = new StringBuilder();
            Dictionary<string, Control>.Enumerator en = controls.GetEnumerator();
            string s;
            int index = 0;

            while (en.MoveNext())
            {
                s = en.Current.Value.Text.Replace("&", "").Replace(" ", "");
                if (s.Equals(part.ToString()))
                    bld.Append(parts[index] + SEPARATOR);

                index++;
            }

            if(bld.Length > 0) bld.Remove(bld.Length - 1, 1);
            return bld.ToString();
        }
        #endregion

        void btn_Click(object sender, EventArgs e)
        {
            selected = (Control)sender;
            selected.ContextMenuStrip.Show(selected, new Point(0, 0));
        }

        void MenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem item = (ToolStripMenuItem)sender;
            controls[selected.Tag.ToString()].Text = item.Text;
        }

        #region Utilities method(s)
        void removeButtonWithTag(string tag)
        {
            foreach (Control ctl in this.Controls)
            {
                if (ctl.GetType().Equals(typeof(Button)))
                {
                    if (ctl.Tag.ToString().Equals(tag))
                        this.Controls.Remove(ctl);
                }
            }
        }
        #endregion

        public bool IsUrlCorrect()
        {
            Dictionary<string, Control>.Enumerator en = controls.GetEnumerator();

            while (en.MoveNext())
            {
                if (string.IsNullOrEmpty(en.Current.Value.Text))
                    return false;
            }

            return true;
        }
    }
}
